package yellow.pe.javaVersion;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * https://pe-cn.github.io/3/
 *
 * Problem 3
 * Largest prime factor
 * The prime factors of 13195 are 5, 7, 13 and 29.
 * What is the largest prime factor of the number 600851475143?
 *
 */
public class PE0003 {
    public static void main(String[] args) {
        //BigInteger b = BigInteger.valueOf(600851475143L);
        BigInteger b = BigInteger.valueOf(13195);
        ArrayList<BigInteger> ab = getPrimeFactors(b);
        BigInteger[] bi = ab.toArray(BigInteger[]::new);
        System.out.println(Arrays.toString(bi));
        System.out.println(bi[bi.length-1]);
    }

    public static ArrayList<BigInteger> getPrimeFactors(BigInteger n) {
        ArrayList<BigInteger> ab = new ArrayList<BigInteger>();
        BigInteger i = BigInteger.TWO;
        while (i.compareTo(n) == -1) {
            BigInteger[] x = n.divideAndRemainder(i);
            if (x[1].equals(BigInteger.ZERO) && isPrimeNumber(i)) {
                ab.add(i);
            }
            i = i.add(BigInteger.ONE);
        }
        return ab;
    }

    public static Boolean isPrimeNumber(BigInteger n) {
        BigInteger i = BigInteger.TWO;
        while (i.compareTo(n) == -1) {
            BigInteger[] x = n.divideAndRemainder(i);
            if (x[1].equals(BigInteger.ZERO)) {
                return false;
            }
            i = i.add(BigInteger.ONE);
        }
        return true;
    }
}
